package org.neogenesis.web.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.parsers.ParserConfigurationException;

import org.neogenesis.web.Configurations;
import org.neogenesis.web.Utils;
import org.neogenesis.web.dao.ArrayExpressDAO;
import org.neogenesis.web.dao.GEOSeriesDAO;
import org.neogenesis.web.loader.arrayExpressLoader.ArrayExpressLoader;
import org.neogenesis.web.loader.arrayExpressLoader.ArrayExpressUtils;
import org.xml.sax.SAXException;

@Named("arrayExpress")
@SessionScoped
public class ArrayExpressController implements Serializable {

	private String rawUrl;

	@Inject
	private ArrayExpressDAO ArrayExpressDAO;

	public ArrayExpressController() {

	}

	public String create() {

		String[] splitUrl = rawUrl.split("/");
		String accessionName = splitUrl[splitUrl.length - 1];

		try {
			if (!ArrayExpressDAO.init(accessionName))
				return "errorInSeries";
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			if (!ArrayExpressDAO.loadPlatforms())
				return "errorLoadPlatform";
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			if (!ArrayExpressDAO.loadExperiment())
				return "duplicateExperiment";
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		try {
			if (!ArrayExpressDAO.loadSamples())
				return "errorLoadSamples";
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		//passare il percorso all'interno di data/files/
		ArrayExpressDAO.deleteFiles();

		Logger.getLogger(GEOSeriesDAO.class.toString()).log(Level.INFO,
				"okSeries");
		
		return "okSeries";
	}

	public String getRawUrl() {
		return rawUrl;
	}

	public void setRawUrl(String rawUrl) {
		this.rawUrl = rawUrl;
	}
}
